package com.zhoug.permission;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Parcel;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Random;
import java.util.UUID;

/**
 * 描述：android 权限申请工具类
 * zhougan
 * 2019/8/2
 **/
public class PermissionUtil {
    private static final String TAG = "PermissionUtil";

    /**
     * 日历
     */
    public static final int CALENDAR = 0;
    /**
     * 相机
     */
    public static final int CAMERA = 1;
    /**
     * 通讯录
     */
    public static final int CONTACTS = 2;
    /**
     * 位置
     */
    public static final int LOCATION = 3;
    /**
     * 麦克风
     */
    public static final int MICROPHONE = 4;
    /**
     * 电话
     */
    public static final int PHONE = 5;
    /**
     * 传感器
     */
    public static final int SENSORS = 6;
    /**
     * 短信
     */
    public static final int SMS = 7;
    /**
     * 存储
     */
    public static final int STORAGE = 8;

    //权限组
    private static final String[][] permissionGroup = new String[][]{
            {Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR},
            {Manifest.permission.CAMERA},
            {Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR},
            {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
            {Manifest.permission.RECORD_AUDIO, Manifest.permission.CAPTURE_AUDIO_OUTPUT, Manifest.permission.MODIFY_AUDIO_SETTINGS},
            {Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE},
            {Manifest.permission.BODY_SENSORS},
            {Manifest.permission.SEND_SMS, Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS, Manifest.permission.BROADCAST_SMS},
            {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},

    };

    /**
     * 用户申请的权限集合
     */
    private int[] permissions;
    private Context mContext;
    private Callback callback;
    private String notAsking = "必须要权限才能正常执行操作";//用户勾选了不在询问后的提示
    private boolean showNotAskingDialig = true;//默认提示
    private RequestPermissionBroadcastReceiver mReceiver;


    public PermissionUtil() {
    }

    public PermissionUtil(Context context) {
        this.mContext = context;
    }

    public PermissionUtil(Context context, int[] permissions) {
        this.mContext = context;
        this.permissions = permissions;
    }




    /**
     * 检查权限是否已经授权
     *
     * @return
     */
    public boolean check() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> realPermissionList = getRealPermissionList();
            //没有添加权限
            if (realPermissionList == null || realPermissionList.size() == 0) {
                return true;
            } else {
                for (String permission : realPermissionList) {
                    if (ActivityCompat.checkSelfPermission(mContext, permission) != PackageManager.PERMISSION_GRANTED) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 权限请求
     */
    public void request() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> shouldRequestPermissions = getShouldRequestPermissions();
            if (shouldRequestPermissions == null || shouldRequestPermissions.size() == 0) {
//                Log.i(TAG, "start: 都已授权");
                if (callback != null)
                    callback.onRequestPermissionsResult(true);
            } else {
                //需要请求权限
//                Log.i(TAG, "start: 需要请求权限: ="+mPermissions.length+"个");
                startPermissionActivity(shouldRequestPermissions);
            }
        } else {
            //6.0以下版本
            if (callback != null)
                callback.onRequestPermissionsResult(true);
        }

    }


    /**
     * 根据权限组获取真正的权限
     *
     * @return
     */
    private ArrayList<String> getRealPermissionList() {
        if (permissions == null || permissions.length == 0) {
            return null;
        }
        //真正的权限数组
        ArrayList<String> permissionArray = new ArrayList<>();
        for (int p : permissions) {
            permissionArray.addAll(Arrays.asList(permissionGroup[p]));
        }
        return permissionArray;
    }


    /**
     * 获取需要申请的权限
     */
    private ArrayList<String> getShouldRequestPermissions() {
        ArrayList<String> realPermissionList = getRealPermissionList();
        if (realPermissionList == null || realPermissionList.size() == 0) {
            return null;
        }
        Iterator<String> iterator = realPermissionList.iterator();
        while (iterator.hasNext()) {
            String permission = iterator.next();
            //移除已经授权的
            if (ActivityCompat.checkSelfPermission(mContext, permission) == PackageManager.PERMISSION_GRANTED) {
                iterator.remove();
            }
        }
        return realPermissionList;
    }

    /**
     * 启动权限申请页面
     *
     * @param permissions
     */
    private void startPermissionActivity(ArrayList<String> permissions) {
        //注册广播
        Log.i(TAG, "startPermissionActivity: 注册广播");
        mReceiver = new RequestPermissionBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        String action = UUID.randomUUID().toString();
        filter.addAction(action);
        mContext.registerReceiver(mReceiver, filter);

        int requestCode = new Random().nextInt(1000);

        Intent intent = new Intent(mContext, PermissionActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putStringArrayListExtra("permissions", permissions);
        intent.putExtra("NotAsking", notAsking);
        intent.putExtra("showNotAskingDialig", showNotAskingDialig);
        intent.putExtra("requestCode", requestCode);
        intent.putExtra("action", action);
        mContext.startActivity(intent);
    }


    //自定义广播接受权限申请结果
    public class RequestPermissionBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (callback == null) {
                mContext.unregisterReceiver(mReceiver);
                return;
            }
            if (intent != null) {
                boolean result = intent.getBooleanExtra("result", false);
                callback.onRequestPermissionsResult(result);
            } else {
                callback.onRequestPermissionsResult(false);
            }
            mContext.unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }

    public interface Callback {

        void onRequestPermissionsResult(boolean success);
    }



    public PermissionUtil addPermissions(int... permissions) {
        this.permissions = permissions;
        return this;
    }

    public Callback getCallback() {
        return callback;
    }

    public PermissionUtil setCallback(Callback callback) {
        this.callback = callback;
        return this;
    }

    public PermissionUtil setContext(Context mContext) {
        this.mContext = mContext;
        return this;
    }

    public PermissionUtil setNotAsking(String notAsking) {
        this.notAsking = notAsking;
        return this;
    }

    public PermissionUtil setShowNotAskingDialig(boolean showNotAskingDialig) {
        this.showNotAskingDialig = showNotAskingDialig;
        return this;
    }

}
